<template>
	<view>
		<!--type-tab 滚定  -->
		<view class="carousel-section" v-if="isShowSticky">
			<view class="titleNview-placing-bar"></view>
			<type-scroll-tabs v-model="tabIndex" :fixed="true" :tabs="homeTabs" @change="ontabchange"></type-scroll-tabs>
		</view>
		<!-- 头部广告轮播 -->
		<view class="carousel-section">
			<!-- 标题栏和状态栏占位符 -->
			<view class="titleNview-placing"></view>
			<!-- 背景色区域 -->
			<view class="titleNview-background" :style="{ backgroundColor: bannerBackground }"></view>
			<swiper class="carousel" style="height: 350rpx;" @change="bannerChange" autoplay="true" interval="3000" duration="300" circular="true">
				<swiper-item v-for="(item, index) in bannerList" :key="index" class="carousel-item" @tap="navTaobao(item)">
					<image :src="item.imageUrl" lazy-load="true" />
				</swiper-item>
			</swiper>
		</view>
		<!-- 滚动消息 -->
		<view class="padding-left margin-top-sm bg-white " v-if="!$store.state.checkMode">
			<swiper style="height: 75rpx; " vertical="true" autoplay="true" circular="true" interval="3000" duration="300">
				<swiper-item v-for="(item, index) in noticeList" :key="index" class="flex align-center">
					<icon-font type="advice" color="#FFA104" size="24"></icon-font>
					<a :href="item.url" style="color:#FFA104; padding-left: 15rpx;">{{ item.name }}</a>
				</swiper-item>
			</swiper>
		</view>
		<!-- 商家导航 -->
		<view class="cate-section" v-if="!$store.state.checkMode">
			<view class="cate-item" v-for="(item, index) in iconList" :key="index" @tap="navTaobao(item)">
				<image :src="item.imageUrl" lazy-load="true"></image>
				<text>{{ item.name }}</text>
			</view>
		</view>
		<!-- 推荐 -->
		<view v-if="!$store.state.checkMode">
			<view class="daleituijian-section">
				<view v-for="(item, index) in broadList" :key="index" class="daleituijian-item" @tap="navTaobao(item)">
					<view class="image-check-wrapper"><image :src="item.imageUrl" mode="widthFix" lazy-load="true"></image></view>
				</view>
			</view>
		</view>
		<!-- 审核模式 -->
		<view class="carousel-section" v-if="$store.state.checkMode">
			<view class="daleituijian-section">
				<view v-for="(item, index) in checkModeList" :key="index" v-if="index < 4" class="daleituijian-item" @tap="navAduit(item.code)">
					<view class="image-check-wrapper"><image :src="item.imageUrl" mode="widthFix" lazy-load="true"></image></view>
				</view>
			</view>
		</view>
		<shop-list v-if="$store.state.checkMode"></shop-list>
		<!-- 推荐类别商品详情 -->
		<view style="margin-bottom: 20rpx;"></view>
		<view id="tabInList"><type-scroll-tabs v-model="tabIndex" :tabs="homeTabs" @change="ontabchange"></type-scroll-tabs></view>
		<mescroll-body ref="mescrollRef" @init="mescrollInit" :down="downOption" :up="upOption" @up="upCallback"><good-list :list="goods"></good-list></mescroll-body>
		<!-- 未登录提示登录 -->
		<view class="login-warn bg-gradual-pink-login flex justify-between align-center radius-top-l" v-show="isLanding">
			<view class="padding-left text-sm">为了保障您的收益，请先登录!</view>
			<view class="padding-right"><button class="cu-btn round bg-black shadow text-sm" hover-class="none" @tap="login">一键登录</button></view>
		</view>
		<dialog-box :modalName="modalName" @cancelLogin="cancelLogin" @login="confrimLogin"></dialog-box>
		<search-clipboard :searchModal="searchModal" @resetModal="resetSearchModal"></search-clipboard>
		<loading :loadModal="loadModal"></loading>
		<tab-bar :current="0"></tab-bar>
	</view>
</template>

<script>
import tabBar from '@/components/tab-bar.vue';
import typeScrollTabs from '@/pages/index/components/type-scroll-tabs.vue';
import goodList from '@/pages/index/components/good-list.vue';
import shopList from '@/pages/index/components/shop-list.vue';
import MescrollMixin from '@/components/mescroll-uni/mescroll-mixins.js';

var _self; //this容器
export default {
	mixins: [MescrollMixin], // 使用mixin (在main.js注册全局组件)
	components: {
		tabBar,
		typeScrollTabs,
		goodList,
		shopList
	},
	data() {
		return {
			bannerList: [],
			bannerBackground: '',
			noticeList: [], //通知
			iconList: [], //五个商家广告
			broadList: [], //六类广告
			isLanding: true, //是否一键登录
			modalName: '', //对话框
			//推荐类目表商品
			homeTabs: [], //{ name: '精选', id: 'jingxuan', goods: null, num: 1, y: 0, curPageLen: 0, hasNext: true }
			tabIndex: 0, // 当前菜单下标
			preIndex: 0, // 前一个菜单下标
			navTop: null, // nav距离到顶部的距离 (如计算不准确,可直接写死某个值)
			isShowSticky: false, // 是否悬浮
			downOption: {
				use: false // 不使用下拉刷新
			},
			upOption: {
				auto: false,
				noMoreSize: 3 //如果列表已无数据,可设置列表的总数量要大于半页才显示无更多数据;避免列表数据过少(比如只有一条数据),显示无更多数据会不好看
			},
			totalPage: 0, //总页数
			searchModal: this.$util.initClipboard(),
			loadModal: false,
			/* 审核模式数据 */
			checkModeList: [],
			shops: []
		};
	},
	computed: {
		// 列表数据
		goods() {
			return this.homeTabs[this.tabIndex] ? this.homeTabs[this.tabIndex].goods : [];
		}
	},
	onLoad() {
		_self = this;
		uni.hideTabBar();
		_self.loadData();
		//console.log(_self.$store.state.version_update , _self.$store.state.version)
		if (_self.$store.state.version_update > _self.$store.state.version) {
			_self.searchModal.type = _self.$store.state.version_force_update ? 'versionNow' : 'version';
		}
	},
	onShow() {
		_self.isLanding = !_self.$util.Landing();
		if (_self.searchModal.type == '') {
			setTimeout(() => {
				_self.$util.searchClipboard(_self.$store.state.searchContent).then(res => {
					_self.searchModal = res;
				});
			}, 200);
		}
	},
	methods: {
		resetSearchModal() {
			_self.searchModal = _self.$util.initClipboard();
		},
		loadData() {
			_self.gethomeList().then(res => {
				_self.mescroll.resetUpScroll();
			});
			_self.getBannerList();
			_self.getNoticeList();
			_self.getIconList();
			_self.getBroadList();
		},
		// 设置nav到顶部的距离 (滚动条为0, 菜单顶部的数据加载完毕获取到的navTop数值是最精确的)
		setNavTop() {
			let view = uni.createSelectorQuery().select('#tabInList');
			view.boundingClientRect(data => {
				this.navTop = data.top + 100; // 到屏幕顶部的距离
			}).exec();
		},
		/* 	获取首页轮播图片 */
		getBannerList() {
			try {
				const param = {
					type: 'Index-Banner'
				};
				_self.$http.httpRequest('advertisement/list', param, false).then(res => {
					if (res._tranStatus) {
						_self.bannerList = res._data.list;
						_self.bannerBackground = _self.bannerList[0].imageColour;
					}
				});
			} catch (e) {
				//console.log('bannerList', e);
			}
		},
		/* 轮播图切换修改背景色 */
		bannerChange(e) {
			_self.bannerBackground = _self.bannerList[e.detail.current].imageColour;
		},
		/* 通知 */
		getNoticeList() {
			try {
				const param = {
					type: 'public_notice'
				};
				_self.$http.httpRequest('advertisement/list', param, false).then(res => {
					if (res._tranStatus) {
						_self.noticeList = res._data.list;
					}
				});
			} catch (e) {
				//console.log('noticeList', e);
			}
		},
		/* 五个栏目图标 */
		getIconList() {
			try {
				const param = {
					type: 'Index-Icon'
				};
				_self.$http.httpRequest('advertisement/list', param, false).then(res => {
					if (res._tranStatus) {
						_self.iconList = res._data.list;
					}
				});
			} catch (e) {
				//console.log('iconList', e);
			}
		},
		/* 推荐 */
		getBroadList() {
			try {
				const param = {
					type: 'Index-Broad'
				};
				_self.$http.httpRequest('advertisement/list', param, false).then(res => {
					if (res._tranStatus) {
						_self.broadList = res._data.list;
					}
				});
			} catch (e) {
				//console.log('broadList', e);
			}
		},
		/* 六类推荐 */
		gethomeList() {
			let promise = new Promise(function(resolve, reject) {
				_self.$http.httpRequest('taobao/productRecommendCatalog/homeList', null, false).then(res => {
					if (res._tranStatus) {
						let tmplist = res._data.list;
						_self.checkModeList = tmplist;
						_self.homeTabs = [];
						tmplist.forEach((item, index) => {
							_self.homeTabs.push({
								code: item.code,
								name: item.name,
								goods: null,
								num: 1,
								y: 0,
								curPageLen: 0,
								hasNext: true
							});
						});
						resolve('sucess');
					}
				});
			});
			return promise;
		},
		//详情页
		navTaobao(item) {
			if (_self.$util.Landing()) {
				if (_self.$util.ExistRelationId()) {
					uni.navigateTo({
						url: 'tbActivity?id=' + item.id
					});
				}
			} else {
				_self.modalName = 'login';
			}
		},
		//审核列表页
		navAduit(code) {
			uni.navigateTo({
				url: '../aduit/list?code=' + code
			});
		},
		//一键登录
		login() {
			uni.navigateTo({
				url: '../access/main'
			});
		},
		//取消登录
		cancelLogin() {
			_self.modalName = '';
		},
		//确认登录
		confrimLogin() {
			_self.modalName = '';
			uni.navigateTo({
				url: '../access/main'
			});
		},

		/*上拉加载的回调: 其中page.num:当前页 从1开始, page.size:每页数据条数,默认10 */
		upCallback(page) {
			//联网加载数据
			if (_self.isChangeTab) {
				_self.mescroll.showUpScroll();
			}
			_self
				.getListDataFromNet(page.num, page.size)
				.then(
					curPageData => {
						_self.loadModal = false;
						let curTab = _self.homeTabs[_self.tabIndex];
						if (page.num == 1) curTab.goods = []; //如果是第一页需手动制空列表
						curTab.goods = curTab.goods.concat(curPageData); //追加新数据
						_self.$nextTick(() => {
							_self.mescroll.endByPage(curPageData.length, _self.totalPage);
							curTab.num = page.num; // 页码
							curTab.curPageLen = curPageData.length; // 当前页长
							curTab.hasNext = _self.mescroll.optUp.hasNext; // 是否还有下一页
							if (_self.isChangeTab) {
								_self.isChangeTab = false;
								_self.mescroll.hideUpScroll();
							}
						});
					},
					error => {
						_self.loadModal = false;
						_self.mescroll.endByPage(0, 0);
						_self.mescroll.hideUpScroll();
					}
				)
				.catch(() => {
					//联网失败, 结束加载
					_self.loadModal = false;
					_self.mescroll.endErr();
				});
		},
		//推荐类别改变说明
		ontabchange(index) {
			// 记录前一个菜单的数据
			let preTab = _self.homeTabs[_self.preIndex];
			preTab.y = _self.mescroll.getScrollTop(); // 滚动条位置
			_self.preIndex = index;
			// 当前菜单的数据
			let curTab = _self.homeTabs[index];
			if (!curTab.goods) {
				// 没有初始化,则初始化
				_self.isChangeTab = true;
				_self.mescroll.resetUpScroll();
			} else {
				// 初始化过,则恢复之前的列表数据
				_self.mescroll.setPageNum(curTab.num + 1); // 恢复当前页码
				_self.mescroll.endSuccess(curTab.curPageLen, curTab.hasNext); // 恢复是否有下一页或显示空布局
				_self.$nextTick(() => {
					_self.mescroll.scrollTo(curTab.y, 0); // 恢复滚动条的位置
				});
			}
		},
		/* 获取查询数据 */
		getListDataFromNet(pageNum, pageSize, successCallback, errorCallback) {
			try {
				const param = {
					currentPage: pageNum,
					pageSize: pageSize,
					condition: {
						catalogId: _self.homeTabs[_self.tabIndex].code
					}
				};
				let promise = new Promise(function(resolve, reject) {
					_self.$http.httpRequest('taobao/productRecommend/catalogProductPagination', param, false).then(res => {
						if (res._tranStatus) {
							_self.totalPage = res._data.totalPage;
							resolve(res._data.pageItems);
						} else {
							let error = {};
							reject('error');
						}
					});
				});
				return promise;
			} catch (e) {
				return Promise.reject(e);
			}
		}
	},
	onPageScroll(e) {
		if (!this.navTop) this.setNavTop();
		if (e.scrollTop >= this.navTop) {
			this.isShowSticky = true; // 显示悬浮菜单
		} else {
			this.isShowSticky = false; // 隐藏悬浮菜单
		}
	},
	onPullDownRefresh() {
		_self.loadData();
		setTimeout(function() {
			uni.stopPullDownRefresh();
		}, 500);
	},
	// #ifndef MP
	// 标题栏input搜索框点击
	onNavigationBarSearchInputClicked: async function(e) {
		uni.switchTab({
			url: '../sou/main?type=0'
		});
	},
	//点击导航栏 buttons 时触发
	onNavigationBarButtonTap(e) {
		/* const index = e.index;
		if (index === 0) {
			this.$api.msg('点击了扫描');
		} else if (index === 1) {
			// #ifdef APP-PLUS
			const pages = getCurrentPages();
			const page = pages[pages.length - 1];
			const currentWebview = page.$getAppWebview();
			currentWebview.hideTitleNViewButtonRedDot({
				index
			});
			// #endif
			uni.navigateTo({
				url: '/pages/notice/notice'
			});
		} */
	}
	// #endif
};
</script>

<style lang="scss">
.login-warn {
	position: fixed;
	bottom: 100rpx;
	z-index: 9997;
	padding: 10rpx;
	width: 100%;

	text-align: center;
}
</style>
